<template>
  <div class="container" style="margin-top: 10px">
    <el-card v-loading="loading ">
      <!-- 表单 -->
      <el-form label-width="70px" :inline="true" :model="form">
        <el-form-item label="标签名称">
          <el-input v-model="form.tagName" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.state">
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handelClear">清除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handelSearch">搜索</el-button>
        </el-form-item>
        <el-form-item class="filter-item fr">
          <el-button v-if="$route.query.id" type="text" @click="$router.push('/subjects/list')"><i class="el-icon-back">返回学科</i></el-button>
          <el-button
          size="small"
          type="success"
          icon="el-icon-edit"
          @click="handelAdd"
            >新增标签</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 数据记录 -->
      <el-alert
        v-if="alertText !== ''"
        :title="alertText"
        type="info"
        class="alert"
        :closable="false"
        show-icon
      ></el-alert>
      <template>
        <!-- 表格 -->
        <el-table :data="tagsList" style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            width="180"
            :index="indexFn"
          >
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科" width="180">
          </el-table-column>
          <el-table-column prop="tagName" label="标签名称"> </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>
          <el-table-column
            prop="addDate"
            label="创建日期"
            :formatter="formatterDate"
          >
          </el-table-column>
          <el-table-column prop="state" label="状态" :formatter="formatterSta">
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" @click="changeState(row)" ref="btn">{{
                row.state === 1 ? "禁用" : "启用"
              }}</el-button>
              <el-button type="text"
              :disabled="row.state === 0"
              @click="handelEdit(row.id)"
                >修改</el-button
              >
              <el-button type="text"
              :disabled="row.state === 0"
              @click="handelDelTag(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    <!-- 分页组件 -->
    <div
      class="pages"
      style="text-algin: right; padding-left: 1000px; margin-top: 20px"
    >
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :total="total"
        :hide-on-single-page="this.tagsList.length <= 1"
        :page-size="pagesize"
        :page-sizes="[5, 10, 20, 30, 50]"
        background
        layout="->,prev, pager, next,sizes, jumper"
      ></el-pagination>
    </div>
    <!-- 弹框 -->
     <div class="container">
     <el-dialog
        title="新增标签"
        :visible="showDialog"
        width="30%"
        @close="handelClose"
      >
      <el-form :model="addForm" :rules="rules" ref="addForm">
        <el-form-item prop="subjectID" label="所属学科">
          <el-select v-model="addForm.subjectID">
            <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
         <el-form-item prop="tagName" label="标签名称"  v-if="!this.$route.query.id">
          <el-input v-model="addForm.tagName" placeholder="请输入标签名称" style="width:230px;"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" >
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="handelSubmit">确 定</el-button>
      </span>
      </el-dialog>
     </div>
    </el-card>
  </div>
</template>

<script>
import { status } from '@/api/hmmm/constants.js'
import { list, changeState, add, detail, update, remove } from '@/api/hmmm/tags.js'
import { simple, detail as detailSub } from '@/api/hmmm/subjects.js'
import dayjs from 'dayjs'
export default {
  data () {
    return {
      status, // 状态
      form: {
        state: '',
        tagName: ''
      },
      page: 1, // 当前页
      pagesize: 10, // 每页条数
      total: 0, // 总条数
      tagsList: [], // 标签列表
      showDialog: false, // 弹框
      addForm: { // 弹框表单
        subjectName: '',
        subjectID: null,
        tagName: ''
      },
      // 校验规则
      rules: {
        subjectID: [{ required: true, message: '所属学科不能为空!', trigger: blur }],
        tagName: [{ required: true, message: '目录名称不能为空!', trigger: blur }]
      },
      subjectList: [], // 学科列表
      loading: false// 加载圈
    }
  },
  computed: {
    // 记录条数
    alertText () {
      return `数据一共${this.total}条`
    }
  },
  methods: {
    // 1.点击清除按钮
    handelClear () {
      this.form = {}
    },
    // 2.点击搜索 根据输入框的值筛选数据进行渲染
    async handelSearch () {
      const obj = {}
      for (const key in this.form) {
        if (this.form[key] !== '') {
          obj[key] = this.form[key]
        }
      }
      const {
        data: { items }
      } = await list({ ...obj })
      this.tagsList = items
      this.page = 1
    },
    // 3.获取标签列表
    async getTagsList () {
      this.loading = true
      const { data: { items, counts } } = await list({ page: this.page, pagesize: this.pagesize })
      this.loading = false
      this.tagsList = items
      this.total = counts
    },
    // 4.处理表格日期格式
    formatterDate (cellValue) {
      return dayjs(cellValue.addDate).format('YYYY-MM-DD HH:mm:ss')
    },
    // 5.处理状态格式
    formatterSta (cellValue) {
      const obj = status.find((item) => item.value === cellValue.state)
      return obj.label
    },
    // 6.监听页数的变化
    handleSizeChange (val) {
      this.pagesize = val
      this.page = 1
      this.getTagsList()
    },
    // 7.监听当前页的变化
    handleCurrentChange (val) {
      const oldPage = this.page
      if (oldPage) {
        // 当前页码为空时
        if (oldPage !== val && val <= this.total) {
          // 当页面发生变化时或者大于等于总页数 更新当前页码
          this.page = val
          this.getTagsList()
        }
      }
    },
    // 8.自定义排序
    indexFn (index) {
      return index + 1 + this.pagesize * (this.page - 1)
    },
    // 9.控制按钮状态
    async changeState (row) {
      if (row.state === 1) {
        await changeState({ id: row.id, state: 0 })
        this.getTagsList()
        this.$message.success('操作成功!')
      } else {
        await changeState({ id: row.id, state: 1 })
        this.getTagsList()
        this.$message.success('操作成功!')
      }
    },
    // 10.添加标签
    handelAdd () {
      this.showDialog = true
      // 获取学科列表
      this.getSubjectList()
    },
    // 11.关闭标签
    handelClose () {
      this.showDialog = false
      // 重置
      this.$refs.addForm.resetFields()
      this.addForm = { // 弹框表单
        subjectName: '',
        subjectID: '',
        tagName: ''
      }
    },
    // 12.获取学科列表渲染下拉框
    async getSubjectList () {
      const { data } = await simple()
      this.subjectList = data
    },
    // 13.标签添加/修改
    handelSubmit () {
      this.$refs.addForm.validate(async flag => {
        if (!flag) return
        if (this.addForm.id) {
          // 修改
          await update({ ...this.addForm })
          this.$message.success('修改成功!')
        } else {
          // 添加
          console.log(this.addForm, '888')
          await add({
            subjectID: +this.addForm.subjectID,
            tagName: this.addForm.tagName
          })
          this.$message.success('添加成功!')
        }
        this.getTagsList()
        this.handelClose()
      })
    },
    // 14.标签修改
    async handelEdit (id) {
      this.showDialog = true
      this.getSubjectList()
      const { data: data1 } = await detail({ id })
      const { data: data2 } = await detailSub({ id: data1.subjectID })
      this.addForm = { tagName: data1.tagName, subjectID: data2.subjectName }
    },
    // 15.删除标签
    handelDelTag (id) {
      if (this.getTagsList.length < 1) {
        this.page--
      }
      this.$confirm('此操作将永久删除改标签,是否继续?', '提示', { type: 'warning' }).then(async () => {
        await remove({ id: id })
        this.getTagsList()
        this.$message.success('删除成功!')
      })
    }
  },
  async created () {
    // 2. 键盘回车事件
    window.onkeydown = function (e) {
      if (e.keyword === 13) {
        this.handleCurrentChang()
      }
    }
    // 路由判断
    console.log(this.$route.query.id, 1111)
    if (this.$route.query.id) {
      const { data: { items, counts } } = await list({ page: this.page, pagesize: this.pagesize, subjectID: this.$route.query.id })
      // this.loading = false
      this.tagsList = items
      this.total = counts
    } else {
      // 1.进页面就获取列表
      this.getTagsList()
    }
  }
}
</script>

<style scoped lang='less'></style>
